package com.ccdt.tv.smartrecommend.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.AppUtils;
import com.ccdt.tv.smartrecommend.model.bean.ControlBean;
import com.ccdt.tv.smartrecommend.service.RecommendService;
import com.google.gson.Gson;

import java.util.ArrayList;

/**
 * 终端控制启动广播
 */
public class TerminalControlReceiver extends BroadcastReceiver {

    private static final String TAG = "TerminalControlReceiver";
    /**
     * 终端控制启动 action
     */
    private static final String ACTION = "com.ccdt.action.AWAKEN_SMART_RECOMMEND";


    private Gson mGson;

    public TerminalControlReceiver() {
        mGson = new Gson();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "onReceive" + intent.getAction());
        if (intent.getAction().equals(ACTION)) {
            //启动 aidl service
//			Intent intentSmartService = new Intent(context, SmartService.class);
//			context.startService(intentSmartService);

            String message = intent.getStringExtra("message");
            Log.w(TAG, "onReceive: message1：" + message);

            String recommendType = intent.getStringExtra("recommend_type");
            String recommendIntent = intent.getStringExtra("recommend_intent");
            String recommendMsg = intent.getStringExtra("recommend_msg");
            String recommendtTime = intent.getStringExtra("recommend_time");

            if (!TextUtils.isEmpty(message)) {
                //进入通过message启动页面
                startByMessage(context,message);

            } else if (!TextUtils.isEmpty(recommendIntent)){
                //第三方启动
                ControlBean bean = new ControlBean();
                bean.setIntent(recommendIntent);
                bean.setType(recommendType);
                bean.setMsg(recommendMsg);
                bean.setTime(recommendtTime);
                startService(context,bean);
            }else{
                //空广播 进入默认页面
                startService(context, null);
            }

        }
    }

    private void startByMessage(Context context, String message) {
        if (message.startsWith("\"") && message.endsWith("\"")) {
            //去掉最外层双引号
            message = message.substring(message.indexOf("\"") + 1, message.lastIndexOf("\""));
            message = message.replace("\\", "");
            Log.w(TAG, "startByMessage: message2:" + message);
        }
        ControlBean bean = null;
        try {
            bean = mGson.fromJson(message, ControlBean.class);
        } catch (Exception e) {
            Log.e(TAG, "onReceive: format active json error");
        }
        if (null != bean) {
            if (null != bean.getFilterList()
                    && bean.getFilterList().size() > 0
                    && !TextUtils.isEmpty(bean.getFilterFlag())
                    && isFilter(bean.getFilterList(), bean.getFilterFlag())) {
                Log.w(TAG, "onReceive: 屏蔽推荐,过滤消息");
                return;
            }
            startService(context, bean);
        } else {
            //广播内容解析失败 进入默认页面
            startService(context, null);
        }
    }

    private void startService(Context context, ControlBean bean) {
        Log.w(TAG, "startService: 发送消息");
        Intent intentRecommendService = new Intent(context, RecommendService.class);
        intentRecommendService.putExtra("recommend_bean", bean);
        context.startService(intentRecommendService);
    }

    /**
     * 将不规则json 转化成可以自动解析的json
     *
     * @param liveJson
     * @return
     */
    private String arrangeLiveIntentJson(String liveJson) {
        String json = liveJson.substring(liveJson.indexOf("intent") + 11, liveJson.lastIndexOf("msg") - 5);
        Log.w(TAG, "arrangeLiveIntentJson:1 " + json);
        json = json.replace("\\", "");
        Log.w(TAG, "arrangeLiveIntentJson:2 " + json);
        json = json.replace("\"{\"serviceid\":\"", "{\"serviceid\":");
        Log.w(TAG, "arrangeLiveIntentJson:3 " + json);
        json = json.replace("\"}\"", "}");
        Log.w(TAG, "arrangeLiveIntentJson:4 " + json);
        Log.w(TAG, "arrangeLiveIntentJson: \"time\" 位置" + liveJson.indexOf("time"));
        return json;
    }

    /**
     * 判断前台APP是否过滤智能推荐浮窗
     *
     * @param filterList 应用包名列表
     * @param filterFlag 过滤规则 0正向过滤 1反向过滤
     * @return true过滤浮窗（不显示） false不过滤浮窗（显示）
     */
    private boolean isFilter(ArrayList<String> filterList, String filterFlag) {
        if (filterFlag.equals("0")) { //正向过滤
            for (String packageName : filterList) {
                Log.w(TAG, "isFilter: 正向过滤 packageName:" + packageName);
                if (AppUtils.isAppForeground(packageName)) {
                    //如果列表中有应用正在运行，则过滤推荐
                    return true;
                }
            }
            return false;
        } else { //反向过滤
            for (String packageName : filterList) {
                Log.w(TAG, "isFilter: 反向过滤 packageName:" + packageName);
                if (AppUtils.isAppForeground(packageName)) {
                    //如果列表中有应用正在运行，则显示推荐
                    return false;
                }
            }
            return true;
        }
    }
}
